/*
 Copyright (c) ILOG 1995-2008.  All rights reserved.

 This source code is intended only as a supplement to ILOG's product documentation.

 THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
 EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
 */

package loan;

import java.io.Serializable;
import java.text.NumberFormat;

/**
 * LoanUtil
 */
public class LoanUtil implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7764736178720624835L;

	/**
	 * Computes the monthly repayment from the loan amount, the number of monthly payments and the yearly interest rate
	 * @param amount the loan amount (double)
	 * @param numberOfMonth the number of monthly payments (int)
	 * @param yearlyRate the yearly interest rate (double)
	 * @return the monthly repayment
	 */
	public static double getMonthlyRepayment(double amount, int numberOfMonth,
			double yearlyRate) {
		double i = yearlyRate / 12;
		double p = i * amount / (1 - Math.pow(1 + i, -numberOfMonth));

		return p;
	}
	
	public static String formattedAmount(double amount) {
		NumberFormat formatter = NumberFormat.getInstance();
		formatter.setMinimumFractionDigits(2);
		formatter.setMaximumFractionDigits(2);
		return formatter.format(amount);
	}
	
	public static String formattedPercentage(double percent) {
		NumberFormat formatter = NumberFormat.getInstance();
		formatter.setMaximumFractionDigits(2);
		return formatter.format(percent*100) + "%";
	}
	
	public static boolean containsOnlyDigits(String string) {
		if (string == null) return false;

		char[] array = string.toCharArray();
		for (int i=0 ; i<array.length; i++) {
			if (!Character.isDigit(array[i]))
				return false;
		}
		return true;
	}
}
